<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\enum\mini\Store as MiniStore;
use app\common\model\DealerGoods;
use app\common\model\Driver;
use app\common\model\Store;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyAuth;
use app\company\model\CompanyOrder;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyUser;
use app\company\model\Delivery;
use app\company\model\ReportGoodsOut;
use app\mini\controller\salesman\Store as SalesmanStore;
use app\Request;
use think\App;
use think\response\Json;
use \think\facade\Db;

/**
 * @ControllerAnnotation(title="看板")
 */
class Kanban extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->each      = true;
        $this->model           = new DealerGoods();
        $this->sort      = ['id' => 'desc'];
    }

    /**
     * @NodeAnnotation (title="仓库概况")
     */
    public function warehouse_overview()
    {
        list($limit, $where) = $this->buildSearchParams();
        // 获取列表数据
        $sql = new DealerGoods();
        if ($this->defaultWhere) $sql = $sql->where($this->defaultWhere);
        $list = $sql->where($where)->field('name,sum(warehouse_stock) as warehouse_stock_sum')->group('name')->paginate()->toArray();
        $new_list =  array_slice($list['data'], 0, 9);
        $qita =   array_slice($list['data'], 9);
        $qita = array_sum(array_column($qita, 'warehouse_stock_sum'));
        array_push($new_list, ['name' => '其他', 'warehouse_stock_sum' => $qita]);
        $list['data'] = $new_list;
        return $this->success($list);
    }


    /**
     * @NodeAnnotation (title="出入库数据")
     */
    public function warehouse_data()
    {
        //出库数据
        $report_goods_out_model   = new ReportGoodsOut();

        $data =  $report_goods_out_model->field('id,big_unit_out_num,middle_unit_out_num,small_unit_out_num,big_unit_out_value,middle_unit_out_value,small_unit_out_value')->select();
        $total_out_num = 0;
        $total_out_money = 0;

        foreach ($data    as $k => $v) {
            $total_out_num =  $v['big_unit_out_num'] + $v['middle_unit_out_num'] + $v['small_unit_out_num'];
            $total_out_money = sprintf("%.2f", $v['big_unit_out_value'] + $v['middle_unit_out_value'] + $v['small_unit_out_value']);
        }
        //入库数据
        $total_in_num = 0;
        $total_in_money = 0;
        //采购入库
        $dealer_order = Db::table('vk_dealer_order');
        $dealer_order_data =  $dealer_order->where($this->defaultWhere)->where([['order_status', '=', 3]])->select()->toArray();

        foreach ($dealer_order_data as $k => $v) {

            $dealer_order_detail_model = Db::table('vk_dealer_order_detail');
            $dealer_order_detail_data = $dealer_order_detail_model->where('dealer_order_id', $v['id'])->withTrashed()->select()->toArray();

            foreach ($dealer_order_detail_data as $k2 => $v2) {
                $total_in_num += $v2['num'];
                $total_in_money += $v2['purchase_total_price'];
            }
        }

        //销退入库
        $company_order_model  = Db::table('vk_company_order');
        $company_order_data =  $company_order_model->where($this->defaultWhere)->where([['out_status', '=', 2]])->select()->toArray();

        foreach ($company_order_data as $k => $v) {
            $company_order_detail_model = Db::table('vk_company_order_detail');
            $company_order_data =  $company_order_detail_model->where([['company_order_id', '=', $v['id']]])->select()->toArray();
            foreach ($company_order_data as $k2 => $v2) {
                $total_in_num += $v2['num'];
                $total_in_money += $v2['total_price'];
            }
        }
        //调拨入库单
        $transfer_order_model = Db::table('vk_company_transfer_order');
        $transfer_order_dtata =  $transfer_order_model->where($this->defaultWhere)->where('check_status', 2)
            ->where('transfer_type', 2)->select()->toArray();


        foreach ($transfer_order_dtata as $k => $v) {

            $transfer_order_detail_model =  Db::table('vk_company_transfer_order_detail');
            $transfer_order_data =  $transfer_order_detail_model->where([['t_oid', '=', $v['id']]])->select()->toArray();
            foreach ($transfer_order_data as $k2 => $v2) {
                $total_in_num += $v2['transfer_num'];
                $dealer_spec_model =  Db::table('vk_dealer_goods_spec');
                $dealer_spec_data =  $dealer_spec_model->where('id', $v2['dealer_goods_spec_id'])->find();
                $total_in_money += $v2['transfer_num'] * $dealer_spec_data['purchase_price'];
            }
        }
        $data = ['total_out_num' => $total_out_num, 'total_out_money' => sprintf("%.2f", $total_out_money), 'total_in_num' => $total_in_num, 'total_in_money' => sprintf("%.2f", $total_in_money)];
        return $this->success($data);
    }

    /**
     * @NodeAnnotation (title="退换货")
     */
    public function return_and_exchange(Request $request)
    {
        $param = $request->get();
        $skip = ceil(($param['page'] - 1) * $param['limit']);
        $company_order_model  = new CompanyOrderDetail();
        $data =  $company_order_model->with([
            'detail'   => function ($query) {
                $query->with([
                    'goods'     => function ($query) {
                        $query->field('id,image,name,code69')->withTrashed();
                    },
                    'goodsSpec' => function ($query) {
                        $query->field('id,image,name,sku,unit')->withTrashed();
                    }
                ]);
            },
            'dealer'   => function ($query) {
                $query->field('id,name');
            },
        ])->where([['goods_type', 'in', [3, 4]]])
            ->where($this->defaultWhere)
            ->order($this->sort)
            ->limit($skip)
            ->paginate($param['limit']);
        return $this->success($data);
    }
    /**
     * @NodeAnnotation (title="配送统计")
     */
    public function shipping_statistics()
    {
        $param = $this->request->get();
        $skip = ceil(($param['page'] ?? 1 - 1) * $param['limit'] ?? 6);
        $list = (new Delivery())->where($this->defaultWhere)->field("FROM_UNIXTIME(create_time, '%Y-%m-%d') AS date,sum(order_num) as order_num ")
            ->order('id desc')->limit($skip)->group("FROM_UNIXTIME(create_time, '%Y-%m-%d')")->paginate($get['limit'] ?? 6)->toArray();
        return $this->success($list);
    }
    /**
     * @NodeAnnotation (title="数据概括")
     */
    public function data_overview()
    {
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        //总配送数
        $data['total_delivery_count'] =  (new Delivery())->where($this->defaultWhere)->count();
        //今日配送数
        $data['today_delivery_count'] =  (new Delivery())->where($this->defaultWhere)->where([["create_time", 'between', [$todayStart, $todayEnd]]])->count();
        //总门店数
        $data['total_store_count'] =  (new Store())->where($this->defaultWhere)->count();
        //今日新增
        $data['today_store_count'] =  (new Store())->where($this->defaultWhere)->where([["create_time", 'between', [$todayStart, $todayEnd]]])->count();
        //总车辆数
        $data['total_driver_count'] =  (new Driver())->where($this->defaultWhere)->count();
        //今日新增
        $data['today_driver_count'] =  (new Driver())->where($this->defaultWhere)->where([["create_time", 'between', [$todayStart, $todayEnd]]])->count();

        return $this->success($data);
    }
    /**
     * @NodeAnnotation (title="门店销售量")
     */
    public function store_sales()
    {

        $order_model = new CompanyOrder();
        $data = $order_model->where($this->defaultWhere)->where([['pid', '>', 0], ['order_status', '=', 2]])->group('store_id')
            ->field('store_id,sum(order_amount) as order_amount_total')->with(['store' => function ($query) {
                $query->field('id, name');
            }])->select();
        return $this->success($data);
    }
    /**
     * @NodeAnnotation (title="门店明细-订单量")
     */
    public function store_details()
    {
        $order_model = new CompanyOrder();
        $data = $order_model->where($this->defaultWhere)->where([['pid', '>', 0], ['order_status', '=', 2]])
            ->field('store_id,sum(order_amount) as order_amount_total,count(id) as order_count')
            ->group('store_id')->with(['store' => function ($query) {
                $query->field('id, name');
            }])->select();
        return $this->success($data);
    }

    /**
     * @NodeAnnotation (title="门店增长量")
     */
    public function store_growth()
    {
        $param = $this->request->get();
        $skip = ceil(($param['page'] ?? 1 - 1) * $param['limit'] ?? 8);
        $list = (new Store())->where($this->defaultWhere)
            ->field("FROM_UNIXTIME(create_time, '%Y-%m-%d') AS date,count(id) as count ")
            ->order('id desc')->limit($skip)->group("FROM_UNIXTIME(create_time, '%Y-%m-%d')")->paginate($get['limit'] ?? 8)->toArray();
        return $this->success([]);
    }

    /**
     * @NodeAnnotation (title="业务员销售明细")
     */
    public function salesperson_sales_details()
    {

        $order_model = new CompanyOrder();
        $data = $order_model->where($this->defaultWhere)->where([['pid', '>', 0], ['order_status', '=', 2]])->group('salesman_id')
            ->field('store_id,sum(order_amount) as order_amount_total')->with(['salesman' => function ($query) {
                $query->field('id, rename');
            }])->select();
        return $this->success($data);
    }

    /**
     * @NodeAnnotation (title="回款数据")
     */
    public function payment_data()
    {
        $order_model = new CompanyOrder();
        $data =  $order_model->where($this->defaultWhere)->field('delivery_amount,order_amount')
        ->where([['pid', '>', 0], ['order_status', '=', 2]])->select()->toArray();
        $new_data['delivery_amount'] = array_sum(array_column($data, 'delivery_amount'));
        $new_data['order_amount'] = array_sum(array_column($data, 'order_amount'));
        return $this->success($new_data);
    }

    /**
     * @NodeAnnotation (title="分红信息")
     */
    public function dividend_information()
    {

        return $this->success([]);
    }

    /**
     * @NodeAnnotation (title="收支概况")
     */
    public function income_and_expenditure_overview()
    {
//系统费用
        return $this->success([]);
    }
}
